import os, unittest

import aphw

class Tests(unittest.TestCase):
    def setUp(self):
        self.env_file = 'test.env'

        if os.path.exists(self.env_file):
            os.remove(self.env_file)

        self.env = aphw.Environment(self.env_file)

    def tearDown(self):
        self.env.close()

        if os.path.exists(self.env_file):
            os.remove(self.env_file)
    
    def test_create_db(self):
        '''Environment.create_db'''
        names = self.env.database_names()
        self.assert_(10 not in names)
        db = self.env.create_db(10)
        db.close()
        names = self.env.database_names()
        self.assert_(10 in names)

    def test_create_db_exists(self):
        '''Create a DB that already exists'''
        db = self.env.create_db(69)
        db.close()
        self.assertRaises(
            KeyError,
            self.env.create_db,
            69)

    def test_open_db(self):
        '''Environment.open_db'''
        self.assert_(42 not in self.env.database_names())
        db = self.env.create_db(42)
        db.close()
        self.assert_(42 in self.env.database_names())
        db = self.env.open_db(42)
        db.close()

    def test_open_nonexistent_database(self):
        '''Open a database that doesn't exist'''
        self.assert_(1234 not in self.env.database_names())
        self.assertRaises(
            KeyError,
            self.env.open_db,
            1234)

    def test_open_db_already_open(self):
        '''Open DB that's already open'''
        with self.env.create_db(101):
            self.assertRaises(
                aphw.StatusError,
                self.env.open_db,
                101)

    def test_open_db_create(self):
        '''open_db that actually creates'''
        self.assert_(3 not in self.env.database_names())
        with self.env.open_db(3, create=True):
            self.assert_(3 in self.env.database_names())
        self.assert_(3 in self.env.database_names())

def suite():
    cases = [Tests]
    suites = [unittest.TestLoader().loadTestsFromTestCase(c) for c in cases]
    return unittest.TestSuite(suites)

if __name__ == '__main__':
    unittest.TextTestRunner(verbosity=2).run(suite())    
